class Assignation < ActiveRecord::Base
	belongs_to :position, :foreign_key => "position_id"	
	belongs_to :member, :foreign_key => "member_id"	        
	belongs_to :ovposition, :foreign_key => "ovposition_id"	        
	#belongs_to :position, :foreign_key => "position_backfill_id"	

	def name 
		"#{position.name} - #{member.name}"
	end

        def validate_on_create
            #Si la position esta utlizada y el record es active, no podemos reutilizarla
	    errors.add("Position:","You must select a position to create an assignation") if not position
	    errors.add("OW Position:","You must select a OW position to create an assignation") if not ovposition
    	    errors.add("Member:","You must select a member to create an assignation") if not member
       	    errors.add("Assignation Date:","You must enter an assignation date to create an assignation") if not assignation_date	    
	    if position and member 
	            errors.add("Position","already in use") if Assignation.find(:all, :conditions => {:position_id => position.id, :active => 1}).size > 0
	            errors.add("Member","already assigned") if Assignation.find(:all, :conditions => {:member_id => member.id, :active=>1}).size > 0
		end
        end
        def backfill
          m = Member.find_by_sql(["SELECT * from members m where id = (select member_id from assignations where position_id = ? and active=0 order by hiring_date DESC LIMIT 1)",position.id])
          if m[0]
            m[0].lastname+", "+m[0].name
          else
            "NA"
          end
          #memberT = Member.find_by_sql(["SELECT m.* FROM members m WHERE m.id = ?",member.id])
          #memberThis.lastname
        end
        def seniority
          position.seniority
        end
        def team
          position.team.name
        end
        def ovposition_position
          position.ovposition.name
        end 
        def technology
          position.technology.name
        end
        def wave
          position.wave.name
        end
         def position_label
          position.position_label
        end
end
